package com.hh.controller;

import com.hh.common.BaseResponse;
import com.hh.common.ErrorCode;
import com.hh.common.ResultUtils;
import com.hh.entity.domain.Blog;
import com.hh.entity.domain.Message;
import com.hh.entity.domain.User;
import com.hh.entity.dto.collect.DoCollectRequest;
import com.hh.entity.enums.BehaviorType;
import com.hh.entity.enums.MessageType;
import com.hh.exception.BusinessException;
import com.hh.exception.ThrowUtils;
import com.hh.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * com.hh.controller
 *
 * @author hanhui
 * @version 0.0.1
 * @date 2025/7/14
 **/
@RestController
@Slf4j
public class UserCollectionController {
    @Resource
    private UserCollectionService userCollectionService;
    @Resource
    private UserService userService;
    @Resource
    private BlogService blogService;
    @Resource
    private MessageService messageService;
    @Resource
    private UserBehaviorService userBehaviorService;

    /**
     * 执行收藏操作
     * 该方法处理用户收藏博客的请求，包括参数校验、执行收藏操作、记录用户行为和发送通知消息
     *
     * @param doCollectRequest 收藏请求参数，包含被收藏的博客ID
     * @param request          HTTP请求对象，用于获取用户登录信息
     * @return BaseResponse<Boolean> 操作结果，成功返回true
     * @throws BusinessException 当请求参数为空或博客ID为空时抛出参数错误异常
     */
    @PostMapping("/collect")
    public BaseResponse<Boolean> doCollection(@RequestBody DoCollectRequest doCollectRequest,
                                              HttpServletRequest request) {
        // 参数校验：检查请求参数和博客ID是否为空
        Long blogId = doCollectRequest.getBlogId();
        if (blogId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 执行收藏操作，如果失败则抛出异常
        boolean success = userCollectionService.doCollect(doCollectRequest, request);
        ThrowUtils.throwIf(Boolean.FALSE.equals(success), ErrorCode.OPERATION_ERROR);
        // 添加行为
        Long userId = userService.getLoginUser(request).getId();
        Long targetId = null;
        Blog byId = blogService.getById(blogId);
        if (byId != null) {
            targetId = byId.getUserId();
        }
        userBehaviorService.addBehavior(userId, blogId, BehaviorType.COLLECT.getValue());

        Message message = Message.builder()
                .type(MessageType.SYSTEM_NOTICE.getValue())
                .userId(targetId)
                .content(String.format("%s收藏了你的", userService.getById(userId).getUserName()))
                .relatedId(blogId)
                .build();
        userBehaviorService.addBehavior(userId, blogId, BehaviorType.LIKE.getValue());
        messageService.sendMessageToUser(message);
        return ResultUtils.success(success);
    }

    /**
     * 取消收藏操作
     *
     * @param doCollectRequest 取消收藏请求参数，包含被取消收藏的博客ID
     * @param request          HTTP请求对象，用于获取用户登录信息
     * @return BaseResponse<Boolean> 操作结果，成功返回true
     * @throws BusinessException 当请求参数为空或博客ID为空时抛出参数错误异常
     */
    @PostMapping("/cancel/collect")
    public BaseResponse<Boolean> cancelCollection(@RequestBody DoCollectRequest doCollectRequest,
                                                  HttpServletRequest request) {
        if (doCollectRequest == null || doCollectRequest.getBlogId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean success = userCollectionService.unCollect(doCollectRequest, request);
        ThrowUtils.throwIf(!success, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取收藏状态
     *
     * @param postId  帖子ID，用于查询是否被当前用户收藏
     * @param request HTTP请求对象，用于获取登录用户信息
     * @return BaseResponse<Boolean> 返回该帖子是否被当前用户收藏
     */
    @GetMapping("/hasCollected/{postId}")
    public BaseResponse<Boolean> getCollectionStatus(@PathVariable Long postId,
                                                     HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        boolean hasCollected = userCollectionService.hasCollected(userId, postId);
        return ResultUtils.success(hasCollected);
    }
}
